package com.fare.taluo.util;

import java.util.Collection;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.MapUtils;


public class PagingUtil {
	
	/**
	 * 取得所需页
	 * @param listToPage
	 * @param T
	 * @param page
	 * @param pageSize
	 * @return
	 */
	public static <T> List<T> paging(List<T> listToPage,Class< ? extends Object> T, long page, long pageSize){
		List<T> resultList = null;
		if(page != 0){
			int ticket = (int) (listToPage.size() - (int)((page-1) * pageSize) - pageSize);
			if(ticket>=0)
				resultList = listToPage.subList((int)((page-1) * pageSize), (int)(page * pageSize));
			else
				resultList = listToPage.subList((int)((page-1) * pageSize), listToPage.size());
		}else{
			resultList = listToPage.subList(0, (int)pageSize);
		}
		return resultList;
	}
	
	/**
	 * 
	 * @param mapToPage
	 * @param T
	 * @param page
	 * @param pageSize
	 * @return
	 */
	public static <T> Map<String, List<T>> paging(Map<String, List<T>> mapToPage,Class< ? extends Object> T, long page, long pageSize){
		if(!MapUtils.isEmpty(mapToPage)){
			for(String key: mapToPage.keySet()){
				mapToPage.put(key, paging(mapToPage.get(key),T, page, pageSize));
			}
			return mapToPage;
		}else{
			return null;
		}
	}
	
	/**
	 * 计算集合的大小
	 * @param collection
	 * @return
	 */
	public static int getTotalPage(Object collection,long rows){
		if(collection instanceof Collection){
			if((int) (((Collection)collection).size()%rows) == 0)
				return (int) (((Collection)collection).size()/rows);
			else
				return (int) (((Collection)collection).size()/rows)+1;
		}else if (collection instanceof Map) {
			if((int) (((Map) collection).keySet().size()%rows) == 0)
				return (int) (((Map) collection).keySet().size()/rows);
			else
				return (int) (((Map) collection).keySet().size()/rows)+1;
		}else{
			return -1;
		}
	}
	
	/**
	 * 取得总行数
	 * @param collection
	 * @return
	 */
	public static int getTotalRows(Object collection){
		if(collection instanceof Collection){
				return (int) ((Collection)collection).size();
		}else if (collection instanceof Map) {
				return (int) ((Map) collection).keySet().size();
		}else{
			return -1;
		}
	}

	/**
	 * 取得总列数
	 * @param collection
	 * @return
	 */
	public static int getTotalRank(Object collection){
		if(collection instanceof Collection){
				return (int) ((Collection)collection).size();
		}else{
			return -1;
		}
	}
}
